package com.keithpower.freshdox;

import bsh.EvalError;
import bsh.Interpreter;
import bsh.TargetError;
import bsh.This;

/**
 * This class is responsible for carrying out tests specified with the Java(BeanShell) key (typically).
 * It works by using the Beanshell interpreter to interpret the code fragment, and then the condition,
 * and uses the value of the last evaluated statement (the condition), to determine whether it
 * passes or not.
 * 
 * @author Keith Power
 *
 */
public class JavaBSHTester extends BasicTestExecuter
{
	/**
	 * Instance of Beanshell Interpreter
	 */
	private Interpreter inp;
	 
	public JavaBSHTester()
	{
		super();

		// TODO class path should really be determined by config property in test tags
		// TODO as should strictness (off by default ?)
		inp = new bsh.Interpreter();
        inp.setClassLoader(ClassLoader.getSystemClassLoader());
        inp.setStrictJava(true);
	}

	public boolean doTest(Test test)
	{
        System.out.println("Doing test: "+test.toString());
        try
        {
            String codeToRun = test.getCode();
            String condition = test.getConditionCode();
            if(condition.length()>0)
            {
                codeToRun += "\n" + condition;
            }
            Object result = inp.eval( codeToRun ); 
            if( result instanceof Boolean)
            {
                boolean answer = ((Boolean)result).booleanValue();
                if(answer==false)
                {
                	setErrorInfo(test, "Test failed");
                }   
//                else
//                {
//                    System.out.println(" [[[[[[[[[[[ TEST PASSED ]]]]]]]]]]");
//                }
                return answer;
            }
            else
            {
            	setErrorInfo(test, "Test executed, but last statement didn't evaluate to a Boolean");
            	return false;
            }
        } catch (TargetError e)
        {
            setErrorInfo(test, "Exception: "+e.getTarget().toString());
        } catch (EvalError e2)
        {
        	setErrorInfo(test, "Evaluation error: "+e2.toString());
            System.out.println("Evaluation error: "+e2.toString());
        }
		return false;
	}

}
